import {Component, OnInit, ViewChild} from '@angular/core';
import {Globals} from '../../../globals';
import {RoleIdEnum} from '../../../enums/role-id.enum';
import {Consts} from '../../../config/consts';
import {PageHelper} from '../../../utils/page-helper-model';
import {ApiUrl} from '../../../config/api-url';
import {BaseService} from '../../../shared/service/base.service';
import {ActivatedRoute, Router} from '@angular/router';
import {FormBuilder, FormGroup} from '@angular/forms';
import {MyDateModel} from '../../../models/my-date.model';

@Component({
  selector: 'app-card-list',
  templateUrl: './device-fault-list.component.html',
  styleUrls: ['./device-fault-list.component.less']
})
export class DeviceFaultListComponent implements OnInit {


  isMobile = Globals.isMobile();
  // 加载状态
  isSpinning: boolean = false;
  // 角色
  roleId: number;
  roleIdEnum = {
    SUPER_ADMINISTRATOR: RoleIdEnum.SUPER_ADMINISTRATOR,
    AGENT: RoleIdEnum.AGENT,
    MERCHANT: RoleIdEnum.MERCHANT,
  };

  // 分页
  pageHelper: PageHelper = new PageHelper;

  listOfData: [];
  // 机构
  agencyList: any;
  // 运营商
  userList: any;

  formModel: FormGroup;
  // 门店
  merchantStoreList: [];
  // 设备类型
  deviceTypeList: [];

  isVisible = false;
  isOkLoading = false;
  id  = -1;
  stateZeroOrNullCount: 0;
  stateEqualsOneCount: 0;
  // 开始日期类型
  startDateTimeType = 'start';
  // 结束日期类型
  endDateTimeType = 'end';

  startDateTime: Date;
  // 结束日期
  endDateTime: Date;

  constructor(private baseService: BaseService, private router: Router, private fb: FormBuilder) {
  }

  submitForm() {
    this.pageHelper.currentPage = 1;
    this.formModel.get('startDate').setValue(this.startDateTime);
    this.formModel.get('endDate').setValue(this.endDateTime);
    this.findList();
    this.findByOne();
  }

  ngOnInit(): void {
    this.buildForm();
    this.roleId = JSON.parse(sessionStorage.getItem(Consts.USER_INFO)).roleId;
    this.startDateTime = this.baseService.zorro.getDateTime().startToday;
    this.endDateTime = this.baseService.zorro.getDateTime().endToday;
    this.formModel.get('startDate').setValue(this.startDateTime);
    this.formModel.get('endDate').setValue(this.endDateTime);
    this.initList();
    this.getAllAgencyOfName();
    this.findAllMerchantStoreByUserInfo();
    this.findAllDeviceType();
    this.getAllUserOfName();
  }

  buildForm() {
    this.formModel = this.fb.group({
      agencyId: ['', []],
      userId: ['', []],
      merchantStoreId: ['-1', []],
      deviceTypeId: ['-1', []],
      state: ['-1', []],
      deviceNo: ['', []],
      startDate: [null, []],
      endDate: [null, []],
    });
  }
  onPageSizeChange(pageSize: any){
    this.pageHelper.pageSize = pageSize;
    this.pageHelper.currentPage = 1;
    this.findList();
  }

  gainAgencyId($event: any) {
    this.getAllUserOfName();
  }

  getAllAgencyOfName() {
    this.baseService.get(ApiUrl.AgencyUrl + '/getAllAgencyOfName').subscribe(data => {
      if (data.status == 0) {
        this.agencyList = data.data;
        let item = {
          id: -1,
          name: '不限'
        };
        this.agencyList.unshift(item);
      } else {
        this.baseService.layer.messageError(data.msg);
      }
    });
  }

  getAllUserOfName() {
    let agencyId = this.formModel.get('agencyId').value;
    if (agencyId == null) {
      agencyId = '0';
    }
    this.baseService.get(ApiUrl.UserUrl + '/getAllUserOfName?agencyId=' + agencyId).subscribe(data => {
      if (data.status == 0) {
        this.userList = data.data;
        let item = {
          id: -1,
          name: '不限'
        };
        this.userList.unshift(item);
      } else {
        this.baseService.layer.messageError(data.msg);
      }
    });
  }

  initList() {
    this.pageHelper.currentPage = 1;
    this.findList();
    this.findByOne();
  }

  nzPageIndexChange($event: number) {
    this.pageHelper.currentPage = $event;
    this.findList();
  }


  findList() {
    this.baseService.findListByMuchCondition(ApiUrl.DeviceFaultRecord + '/findDeviceFaultRecordList', this.formModel.value, this.pageHelper).subscribe(
      data => {
        if (data.status == 0) {
          this.pageHelper.totalItems = data.data.total;
          this.pageHelper.numPages = data.data.pages;
          this.listOfData = data.data.list;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }
  findByOne() {
    this.baseService.findListByMuchCondition(ApiUrl.DeviceFaultRecord + '/statRecord', this.formModel.value).subscribe(
      data => {
        if (data.status == 0) {
          this.stateZeroOrNullCount = data.data.stateZeroOrNullCount;
          this.stateEqualsOneCount = data.data.stateEqualsOneCount;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }
  findAllMerchantStoreByUserInfo() {
    let userId = this.formModel.get('userId').value;
    if (userId == null) {
      userId = '';
    }
    this.baseService.get(ApiUrl.MerchantStoreUrl + '/findAllMerchantStoreByUserInfo?userId=' + userId).subscribe(
      data => {
        if (data.status == 0) {
          this.merchantStoreList = data.data;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }

  findAllDeviceType() {
    this.baseService.get(ApiUrl.DeviceTypeUrl + '/findAllDeviceType').subscribe(
      data => {
        if (data.status == 0) {
          this.deviceTypeList = data.data;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }
  showModal(data): void {
    this.isVisible = true;
    this.id = data.id;
  }

  handleOk(): void {
    this.isOkLoading = true;
    this.updateState();
  }

  handleCancel(): void {
    this.isVisible = false;
    this.isOkLoading = false;
    this.id = -1;
  }
  updateState() {
    if (this.id == null || this.id == -1){
      return;
    }
    let params = {
      id: this.id
    };
    this.baseService.post(ApiUrl.DeviceFaultRecord + '/updateState', params).subscribe(
      data => {
        if (data.status == 0) {
          this.baseService.layer.messageSuccess('处理完成');
          this.initList();
          this.handleCancel();
        } else {
          this.handleCancel();
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }
  // 将开始、结束时间往外抛
  outDateTime($event: MyDateModel) {
    /**
     * date: Fri Mar 19 2021 23:59:06 GMT+0800 (中国标准时间) {}
     * type: "end"
     */
    if ($event.type == 'start') {
      this.startDateTime = $event.date;
    } else if ($event.type == 'end') {
      this.endDateTime = $event.date;
    }
  }
}
